<?php
namespace core;

/**
 * 处理Lib的类
 */
class Lib
{
  static private $loadList=array();
  static private $template=array(//引入模板，
		'js'=>'<script src="{file}"></script>',
		'css'=>'<link href="{file}" rel="stylesheet">',
		'less'=>'<link rel="stylesheet/less" type="text/css" href="{file}" />',
	);
  static public $group=array();
  static public $lib=array();

  // 增加lib
  static function addLib($key,$items){
		$items=Func::str2arr($items);
    if (!isset(self::$lib[$key])) self::$lib[$key]=array();
    self::$lib[$key]=array_merge(self::$lib[$key],$items);
	}
  // 增加组
	static function addGroup($key,$items){

    $items=Func::str2arr($items);
    if (!isset(self::$group[$key])) self::$group[$key]=array();
    self::$group[$key]=array_merge(self::$group[$key],$items);
	}
  static function hash($name){
		return md5($name);
	}
  // 加载lib
  static function load($name,$base=""){
    $list=(is_array($name))?$name:explode(',',$name);
    $htmls='';
    foreach ($list as $l) {
      $l=trim($l);
			if (empty(self::$group[$l])){
				if (!empty(self::$lib[$l])){
					$htmls.=self::loadLibFile(self::$lib[$l],$base);
				}
			}else{
				foreach(self::$group[$l] as $rl){
					$htmls.=self::loadLibFile(self::$lib[$rl],$base);
				}
			}

		}
    // Debug::log("Libs:","输出lib到浏览器");
		return $htmls;
	}
  // 加载一个lib
  static function loadLibFile($rl,$base){

		$htmls='';

    foreach ($rl as $file) {
      if (empty($file)) continue;
      $path=(empty($base))?$file:rtrim($base,'/').'/'.ltrim($file,'/');
      $hash=self::hash($path);
      if (!in_array($hash,self::$loadList)){
        self::$loadList[]=$hash;
        $e=pathinfo($path, PATHINFO_EXTENSION);
        if (isset(self::$template[$e])){
          $htmls.=str_replace('{file}',$path,self::$template[$e])."\n";
          // Debug::log("Libs:","加载lib",$path);
        }
      }
    }

		return $htmls;

	}



}
?>
